package com.xyzwps.paimon.furina.modules

import com.xyzwps.paimon.furina.common.wrapError
import com.xyzwps.paimon.furina.infra.injectValidator
import com.xyzwps.paimon.furina.modules.auth.app.AuthApis
import com.xyzwps.paimon.furina.modules.debug.app.DebugApis
import com.xyzwps.paimon.furina.modules.me.MeApis
import com.xyzwps.paimon.furina.modules.post.PostApis
import com.xyzwps.paimon.furina.modules.tag.TagApis
import jakarta.validation.Validator
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.function.RouterFunction
import org.springframework.web.servlet.function.ServerResponse
import org.springframework.web.servlet.function.RouterFunctions.route

@Configuration
class MainRouter(
    private val authApis: AuthApis,
    private val debugApis: DebugApis,
    private val meApis: MeApis,
    private val postApis: PostApis,
    private val tagApis: TagApis,
    private val validator: Validator,
) {

    @Bean
    fun router(): RouterFunction<ServerResponse> {
        val that = this

        return route()
            .path("/api/auth", authApis::router)
            .path("/api/me", meApis::router)
            .path("/api/posts", postApis::postRouter)
            .path("/api/post-collections", postApis::collectionRouter)
            .path("/api/tags", tagApis::router)
            .filter { req, next ->
                req.injectValidator(validator)
                try {
                    next.handle(req)
                } catch (e: Throwable) {
                    wrapError(e, req)
                }
            }
            .build()

        /*
        val routexx = router {
            "/api/auth".nest(authApis.route())
            "/api/debug".nest(debugApis.route())
            "/api/me".nest(meApis.route())
            "/api/posts".nest(postApis.postRoute())
            "/api/post-collections".nest(postApis.collectionRoute())
            "/api/tags".nest {
                tagApis.rf()
            }
            filter { req, next ->
                req.injectValidator(validator)
                try {
                    next(req)
                } catch (e: Throwable) {
                    wrapError(e, req)
                }
            }
        }
        return routexx

         */
    }
}